package com.thz.websqlit.common.util;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public final class FileImageUtil {
    /**
     *按宽比例缩小
     * @param inputStream
     * @param width
     * @param suffix 文件格式，pdf，jpg
     * @return
     */
    public static ByteArrayInputStream scaleImage(InputStream inputStream, int width, String suffix) {
        BufferedImage bufferedImage;
        try {
            bufferedImage = ImageIO.read(inputStream);
            int heightImg = bufferedImage.getHeight();
            int widthImg = bufferedImage.getWidth();
            int height = heightImg*width/widthImg;
            Image image = bufferedImage.getScaledInstance(width, height,
                    Image.SCALE_SMOOTH);

            BufferedImage outputImage = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics graphics = outputImage.getGraphics();
            graphics.drawImage(image, 0, 0, null);
            graphics.dispose();
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(bufferedImage, suffix, imOut);
            return new ByteArrayInputStream(bs.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
